package huu.eventLoop;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author huu
 * @create 2025-08-28-14:44
 */
public class huuEventLoopGroup implements EventLoopGroup{
    private final EventLoop[] children;
    private final AtomicInteger index = new AtomicInteger();

    public huuEventLoopGroup(int numThreads) {
        children = new EventLoop[numThreads];
        for (int i = 0; i < numThreads; i++) {
            children[i] = new huuEventLoop();
        }
    }
    @Override
    public void execute(Runnable runnable) {
        if (runnable instanceof TargetRunnable targetRunnable) {
            children[targetRunnable.getIndex()].execute(targetRunnable);
        } else {
            next().execute(runnable);
        }
    }

    @Override
    public void schedule(Runnable runnable, long delay, TimeUnit unit) {
        if (runnable instanceof TargetRunnable targetRunnable) {
            children[targetRunnable.getIndex()].schedule(runnable, delay, unit);
        } else {
            next().schedule(runnable, delay, unit);
        }
    }

    @Override
    public void scheduleAtFixedRate(Runnable runnable, long initialDelay, long period, TimeUnit unit) {
        if (runnable instanceof TargetRunnable targetRunnable) {
            children[targetRunnable.getIndex()].scheduleAtFixedRate(runnable, initialDelay, period, unit);
        } else {
            next().scheduleAtFixedRate(runnable, initialDelay, period, unit);
        }
    }

    @Override
    public EventLoop next() {
        return children[Math.abs(index.getAndIncrement() % children.length)];
    }
}
